﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;

namespace VSM
{
    public partial class WSCB : System.Web.UI.Page
    {
      
        private static string dbType;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[Utils.AppConstants.ID_User] == null
                          || Session[Utils.AppConstants.Password] == null
                          || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("../../Login.aspx");
            }
            if (!IsPostBack)
            {
                dbType = Session[VSM.Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? VSM.Utils.AppConstants.VSM : VSM.Utils.AppConstants.DEALER;

                Session["ServiceID"] = Request.QueryString["ServiceID"] == null ? "" : Request.QueryString["ServiceID"];

                loadWSCB();
            }
        }

        private void loadDefaultNew()
        {
            DateTime currDate = DateTime.Now;
            txtDate.Text = currDate.ToString("dd/MM/yyyy");
            Session["ServiceID"] = "";
            Services sv = new Services();
            string sqlDealer = "select CardCode, CardName from OCRD where CardCode = '" + Session[VSM.Utils.AppConstants.ID_Dealer] + "'";
            DataSet dsDealer = sv.ExecuteQuery("VSM", sqlDealer);
            if (dsDealer.Tables[0].Rows.Count > 0)
            {
                txt_DealerCode.Text = dsDealer.Tables[0].Rows[0]["CardCode"].ToString();
                txt_DealerName.Text = dsDealer.Tables[0].Rows[0]["CardName"].ToString();
            }

            string sqlSeqNo = "select RIGHT('000' + cast((count(GeneralID)+1) as nvarchar(10)), 4) as NewSeqNo from U_GeneralService ";
            sqlSeqNo += " where JobKind = '004' and DealerCode = '" + Session[VSM.Utils.AppConstants.ID_Dealer] + "' and year(ServiceDate) = " + currDate.Year;
            DataSet dsSeq = sv.ExecuteQuery("DEALER", sqlSeqNo);
            if (dsSeq.Tables[0].Rows.Count > 0)
            {
                txt_SeqNo.Text = dsSeq.Tables[0].Rows[0]["NewSeqNo"].ToString();
            }

            string sqlDet = "SELECT [DetID],[GeneralID],[VIN],cast([KD] as bit) as KD,[RepairDate],[OrderNum],[Hour],[Amount], 0 No ";
            sqlDet += " FROM [Dealer_Test].[dbo].[U_WSCBDetail] where GeneralID = -1";


            Session["dtDetail"] = sv.ExecuteQuery("DEALER", sqlDet).Tables[0];
            grvPO.DataSource = (DataTable)Session["dtDetail"];
            grvPO.DataBind();

        }

        private void loadWSCB()
        {
            if (Session["ServiceID"].ToString() == "")
            {
                loadDefaultNew();
            }
            else
            {
                string sql = "select GeneralID, ServiceDate, RegistrationNum, DisCode, DisName, DealerCode, DealerName, ";
                sql += " SeqNo, S, ID, T, WSCBRemarks, WSCType  ";
                sql += " from U_GeneralService ";
                sql += " where GeneralID = " + Session["ServiceID"].ToString();
                Services sv = new Services();
                DataSet ds = sv.ExecuteQuery("DEALER", sql);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    txtDate.Text = FormatDate(ds.Tables[0].Rows[0]["ServiceDate"].ToString());
                    txt_RegistrationNum.Text = ds.Tables[0].Rows[0]["RegistrationNum"].ToString();
                    txt_DistCode.Text = ds.Tables[0].Rows[0]["DisCode"].ToString();
                    txt_DistName.Text = ds.Tables[0].Rows[0]["DisName"].ToString();
                    txt_DealerCode.Text = ds.Tables[0].Rows[0]["DealerCode"].ToString();
                    txt_DealerName.Text = ds.Tables[0].Rows[0]["DealerName"].ToString();
                    txt_SeqNo.Text = ds.Tables[0].Rows[0]["SeqNo"].ToString();
                    txt_S.Text = ds.Tables[0].Rows[0]["S"].ToString();
                    txt_Type.Text = ds.Tables[0].Rows[0]["T"].ToString();
                    txt_Notice.Text = ds.Tables[0].Rows[0]["WSCBRemarks"].ToString();

                    string sqlDet = " SELECT ROW_NUMBER() OVER (ORDER BY DetID) AS No, ";
                    sqlDet += "[DetID],[GeneralID],[VIN],cast([KD] as bit) as KD,[RepairDate],[OrderNum],[Hour],[Amount] ";
                    sqlDet += " FROM [U_WSCBDetail] where Status = 0 AND GeneralID = " + Session["ServiceID"];

                    Session["dtDetail"]= sv.ExecuteQuery("DEALER", sqlDet).Tables[0];
                    grvPO.DataSource = (DataTable)Session["dtDetail"];
                    grvPO.DataBind();
                }
            }
        }

        private string FormatDate(string dateIn)
        {
            if (dateIn.Trim() == "")
                return "";
            DateTime pars = DateTime.Parse(dateIn);
            return pars.ToString("dd/MM/yyyy");

        }

        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                saveGrid();
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lblNo");
                int rowNo = Int32.Parse(lblNo.Text);
                DataTable dtTmp = (DataTable)Session["dtDetail"];
                Services sv = new Services();
                foreach (DataRow dr in dtTmp.Rows)
                {
                    if (rowNo == Int32.Parse(dr["No"].ToString()))
                    {
                        string DetID = dr["DetID"].ToString();
                        if (DetID != "-1") {
                            DataSet dsDel = new DataSet();
                            DataTable dtDel = new DataTable();
                            dtDel.Columns.Add("DetID");
                            DataRow drDel = dtDel.NewRow();
                            drDel["DetID"] = DetID;

                            dtDel.Rows.Add(drDel);
                            dsDel.Tables.Add(dtDel);

                            sv.DeleteWSCBDetail("DEALER", dsDel);
                        }
                        dr.Delete();

                        break;
                    }
                }
                //reset number
                int index = 0;
                foreach (DataRow dr in dtTmp.Rows)
                    dr["No"] = ++index;

                Session["dtDetail"] = dtTmp;
                grvPO.DataSource = dtTmp;
                grvPO.DataBind();
                
            }
            catch (Exception ex)
            {
                //this.lblError.Text = ex.Message;
                //this.lblError.Visible = true;
            }

        }

        protected void TextBox_Change(object sender, EventArgs e)
        {
            TextBox tb = (TextBox)sender;
            string FRTCode = tb.Text;
            GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
            Label lblNo = (Label)row.FindControl("lblNo");
            int rowNo = Int32.Parse(lblNo.Text) - 1;
            int index = 0;
            /*
            foreach (DataRow dr in dtDetail.Rows)
            {
                if (rowNo == index)
                {

                    Services sv = new Services();

                    DataSet dsItem = sv.ExecuteQuery(dbType, "select * from U_FRT where FRTCode like '%" + FRTCode + "%'");

                    if (dsItem.Tables[0].Rows.Count == 1)
                    {
                        dr["FRTID"] = dsItem.Tables[0].Rows[0]["FRTID"];
                        dr["PositionCode"] = dsItem.Tables[0].Rows[0]["FRTCode"];
                        dr["Quantity"] = dsItem.Tables[0].Rows[0]["FRTValue"];
                        double lbCharge = Double.Parse(dsItem.Tables[0].Rows[0]["FRTValue"].ToString());
                        dr["LabourCharge"] = lbCharge * 120;
                        dr["FRTName"] = dsItem.Tables[0].Rows[0]["FRTName"];

                        grvPO.DataSource = dtDetail;
                        grvPO.DataBind();

                        this.lb_Message.Visible = false;
                        break;
                    }
                    else if (dsItem.Tables[0].Rows.Count > 1)
                    {
                        string msg = "Available parts: ";
                        foreach (DataRow drItem in dsItem.Tables[0].Rows)
                        {
                            msg += drItem["FRTCode"].ToString() + ", ";
                        }
                        this.lb_Message.Text = msg;
                        this.lb_Message.Visible = true;
                        break;
                    }
                    else
                    {
                        this.lb_Message.Text = "There is no job with code [" + FRTCode + "] available";
                        this.lb_Message.Visible = true;
                    }
                }
                index++;
            }
           */

        }

        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                ViewState["rowindex"] = e.RowIndex;
                GridViewRow row = null;// = (GridViewRow)this.grvPO.Rows[e.RowIndex];
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0 || int.Parse(txtQuantity.Text.Trim()) == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('In Quantity column, enter whole number greater than 0');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        //GetPrice(rupdate[0]);
                    }

                    //this.grvPO.EditIndex = -1;

                    //BindData(tb);
                    //CalcTotal(tb);
                }
            }
            catch (Exception ex)
            {
                this.lb_Message.Text = ex.Message;
                this.lb_Message.Visible = true;
            }
        }

        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            /*
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        updateRowTotalPrice(rupdate[0], "Quantity");
                    }
                }

                //this.grvPO.EditIndex = -1;

                //BindData(tb);
                //CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            */
        }

        protected void txtUnitPrice_OnTextChanged(object sender, EventArgs e)
        {
            /*
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtUnitPrice = (TextBox)row.FindControl("txtUnitPrice");
                if (txtUnitPrice.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtUnitPrice.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["PriceBefDi"] = txtUnitPrice.Text;
                        updateRowTotalPrice(rupdate[0], "PriceBefDi");
                    }
                }

                //this.grvPO.EditIndex = -1;

                //BindData(tb);
                //CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
             * */
        }

        private void saveGrid() {
            DataTable dtTmp = (DataTable)Session["dtDetail"];
            dtTmp.Rows.Clear();

            foreach (GridViewRow row in grvPO.Rows)
            {
                DataRow newRow = dtTmp.NewRow();
                newRow["No"] = ((Label)row.FindControl("lblNo")).Text;
                newRow["DetID"] = ((Label)row.FindControl("lbDetID")).Text;
                newRow["VIN"] = ((TextBox)row.FindControl("txt_VIN")).Text;
                newRow["KD"] = ((CheckBox)row.FindControl("chk_KD")).Checked==true?1:0;

                string dateStr = ((TextBox)row.FindControl("txt_RepairDate")).Text;
                if (dateStr == "")
                    newRow["RepairDate"] = DBNull.Value;
                else
                    newRow["RepairDate"] = Utils.AppConstants.ConvertToDate(dateStr);

                newRow["OrderNum"] = ((TextBox)row.FindControl("txt_OrderNum")).Text;
                newRow["Hour"] = ((TextBox)row.FindControl("txt_Hour")).Text;
                newRow["Amount"] = ((TextBox)row.FindControl("txt_Amount")).Text;

                dtTmp.Rows.Add(newRow);
            }

            Session["dtDetail"] = dtTmp;
        }

        protected void btn_LabourAdd_Click(object sender, EventArgs e)
        {
            //DateTime currDate = DateTime.Now;
            saveGrid();

            DataTable dtTmp = (DataTable)Session["dtDetail"];
            DataRow dr = dtTmp.NewRow();
            dr["DetID"] = -1;
            dr["No"] = dtTmp.Rows.Count + 1;
            dr["VIN"] = "";
            dr["RepairDate"] = DateTime.Now;
            dr["KD"] = false;
            dr["OrderNum"] = "";
            dr["Hour"] = 0;
            dr["Amount"] = 0;
            dtTmp.Rows.Add(dr);

            Session["dtDetail"] = dtTmp;
            this.grvPO.DataSource = dtTmp;
            this.grvPO.DataBind();
        }

        private void WSCBAddnew() {
            DataSet dsMaster = new DataSet();
            DataTable dtMaster = new DataTable();
            dtMaster.Columns.Add("ServiceDate");
            dtMaster.Columns.Add("RegistrationNum");
            dtMaster.Columns.Add("DisCode");
            dtMaster.Columns.Add("DisName");
            dtMaster.Columns.Add("DealerCode");
            dtMaster.Columns.Add("DealerName");
            dtMaster.Columns.Add("SeqNo");
            dtMaster.Columns.Add("S");
            dtMaster.Columns.Add("ID");
            dtMaster.Columns.Add("T");
            dtMaster.Columns.Add("WSCBRemarks");

            DataRow drMaster = dtMaster.NewRow();

            if (txtDate.Text.Trim() == "")
                drMaster["ServiceDate"] = DBNull.Value;
            else
                drMaster["ServiceDate"] = Utils.AppConstants.ConvertToDate(txtDate.Text.Trim());

            drMaster["RegistrationNum"] = txt_RegistrationNum.Text;
            drMaster["DisCode"] = txt_DistCode.Text;
            drMaster["DisName"] = txt_DistName.Text;
            drMaster["DealerCode"] = txt_DealerCode.Text;
            drMaster["DealerName"] = txt_DealerName.Text;
            drMaster["SeqNo"] = txt_SeqNo.Text;
            drMaster["S"] = txt_S.Text;
            drMaster["ID"] = txt_ID.Text;
            drMaster["T"] = txt_Type.Text;
            drMaster["WSCBRemarks"] = txt_Notice.Text;

            dtMaster.Rows.Add(drMaster);
            dsMaster.Tables.Add(dtMaster);

            Services sv = new Services();
            int newID = sv.InsertWSCB("DEALER", dsMaster);
            if (newID != -1)
            { //add new complete
                Session["ServiceID"] = newID;
                WSCBDetailAddUpdate();
                loadWSCB();
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('[Add new] Operation complete','');", true);
            }
            else {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('[Add new] Operation not complete','');", true);
            }
        }

        private void WSCBUpdate()
        {
            DataSet dsMaster = new DataSet();
            DataTable dtMaster = new DataTable();
            
            dtMaster.Columns.Add("S");
            dtMaster.Columns.Add("ID");
            dtMaster.Columns.Add("T");
            dtMaster.Columns.Add("WSCBRemarks");
            dtMaster.Columns.Add("GeneralID");

            DataRow drMaster = dtMaster.NewRow();

           
            drMaster["S"] = txt_S.Text;
            drMaster["ID"] = txt_ID.Text;
            drMaster["T"] = txt_Type.Text;
            drMaster["WSCBRemarks"] = txt_Notice.Text;
            drMaster["GeneralID"] = Session["ServiceID"];
            dtMaster.Rows.Add(drMaster);
            dsMaster.Tables.Add(dtMaster);

            Services sv = new Services();
            int count = sv.UpdateWSCB("DEALER", dsMaster);
            if (count > 0)
            { //add new complete
                WSCBDetailAddUpdate();
                loadWSCB();
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('[Update] Operation complete','');", true);
            }
            else
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('[Update] Operation not complete','');", true);
            }
        }

        private void WSCBDetailAddUpdate() {
            Services sv = new Services();
            DataTable dt = (DataTable)Session["dtDetail"];

            DataSet dsAdd = new DataSet();
            DataTable dtAdd = new DataTable();
            dtAdd.Columns.Add("GeneralID");
            dtAdd.Columns.Add("VIN");
            dtAdd.Columns.Add("KD");
            dtAdd.Columns.Add("RepairDate");
            dtAdd.Columns.Add("OrderNum");
            dtAdd.Columns.Add("Hour");
            dtAdd.Columns.Add("Amount");
            dtAdd.Columns.Add("DetID");
     
            foreach (DataRow dr in dt.Rows) {
                dtAdd.Rows.Clear();
                DataRow drAdd = dtAdd.NewRow();
                drAdd["GeneralID"] = Session["ServiceID"];
                drAdd["VIN"] = dr["VIN"];
                drAdd["KD"] = dr["KD"].ToString()=="True"?1:0;
                drAdd["RepairDate"] = dr["RepairDate"];
                drAdd["OrderNum"] = dr["OrderNum"];
                drAdd["Hour"] = dr["Hour"];
                drAdd["Amount"] = dr["Amount"];
                drAdd["DetID"] = dr["DetID"];
                dtAdd.Rows.Add(drAdd);
                dsAdd.Tables.Clear();
                dsAdd.Tables.Add(dtAdd);
                if (dr["DetID"].ToString() == "-1")//add new
                {
                    sv.InsertWSCBDetail("DEALER", dsAdd);
                }
                else
                {
                    sv.UpdateWSCBDetail("DEALER", dsAdd);
                }
            }
        }

        protected void btn_Save_Click(object sender, EventArgs e)
        {
            saveGrid();
            if (Session["ServiceID"].ToString() == "")
                WSCBAddnew();
            else
                WSCBUpdate();
            /*
            Services sv = new Services();
            DataSet dsDetail = new DataSet();
            DataTable dtAdd = new DataTable();
            dtAdd.Columns.Add("FRTID");
            dtAdd.Columns.Add("PositionCode");
            dtAdd.Columns.Add("Quantity");
            dtAdd.Columns.Add("LabourCharge");
            dtAdd.Columns.Add("GeneralID");

            foreach (DataRow dr in dtDetail.Rows) {
                if (dr.RowState == DataRowState.Added)
                {
                    dsDetail.Tables.Clear();
                    dtAdd.Rows.Clear();
                    DataRow drAdd = dtAdd.NewRow();
                    drAdd["FRTID"] = dr["FRTID"];
                    drAdd["PositionCode"] = dr["PositionCode"];
                    drAdd["Quantity"] = dr["Quantity"];
                    drAdd["LabourCharge"] = dr["LabourCharge"];
                    drAdd["GeneralID"] = Session["ServiceID"];
                    dtAdd.Rows.Add(drAdd);
                    dsDetail.Tables.Add(dtAdd);
                    sv.InsertGeneralServiceLabour(dbType, dsDetail);
                }
                
            }
            this.lb_Message.Text = "Update complete.";
            this.lb_Message.Visible = true;
             * */
        }

       

       
        protected void btn_ImportExcel_Click(object sender, EventArgs e)
        {

        }


        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //if(e.Row.RowType== DataControlRowType.DataRow){
            //    TextBox ddl1 = e.Row.FindControl("txtItemCode") as TextBox;
            //    ddl1.Attributes.Add("onkeydown", "return (event.keyCode!=13);");
            //}
        }

        protected void btn_New_Click(object sender, EventArgs e)
        {
            loadDefaultNew();
        }
    }
}